﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace TMV.Application.WebService.Services
{
    public class WebServiceDM : IWebServiceDM, IDynamicApiController, ITransient
    {
        IHttpClientFactory _httpClientFactory;
        public WebServiceDM(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        /// <summary>
        /// 封装使用HttpClient调用WebService
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="content">参数</param>
        /// <returns></returns>
        private async Task<string> PostHelper(string url, HttpContent content)
        {
            var result = string.Empty;
            try
            {
                using (var client = _httpClientFactory.CreateClient())
                using (var response = await client.PostAsync(url, content))
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        result = await response.Content.ReadAsStringAsync();
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(result);
                        result = doc.InnerText;
                    }
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }
        [HttpPost]
        public async Task<string> selectcityPost(string byProvinceName)
        {
            string strResult = "";
            try
            {
                // url地址格式：WebService地址+方法名称     
                // WebService地址：http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
                // 方法名称： getSupportCity
                string url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity";
                // 参数
                Dictionary<string, string> dicParam = new Dictionary<string, string>();
                //参数名
                dicParam.Add("byProvinceName", byProvinceName);
                // 将参数转化为HttpContent
                HttpContent content = new FormUrlEncodedContent(dicParam);
                strResult = await PostHelper(url, content);
            }
            catch (Exception ex)
            {
                strResult = ex.Message;
            }

            return strResult;
        }
    }
}
